/*基金-基金赎回页面 path: '/fundredeem'*/
<template>
  <div class="fund-redeem common-fun-trade" :class="{fixed: isSearch}">
    <header-top :option="headerOption"></header-top>

    <div class="container_redeem">
      <!-- 基金代码和赎回份额输入框 -->
      <div class="redeem_t">
        <!-- 基金代码输入框 -->
        <div class="redeem_t_t">
          <div class="title_redeem"><span></span>基金代码</div>
          <div class="input_redeem fund_code">
            <input type="text" placeholder="请输入基金简拼/基金代码" @click.stop.prevent="search" @input="search" v-model="fund_code" />
            <i class="iconfont icon-qingkong cancel" v-show="fund_code != ''" @click="clearInput"></i>
          </div>
          <div class="mark_redeem" v-show="fund_code != '' && redemptionFund.last_price != ''">
            <p>净值<span> {{redemptionFund.last_price}} </span><span>{{redemptionFund.ofstatue | getStatusName}}</span></p>
            <p>此净值仅供参考，最终以产品管理人公布数据为准</p>
          </div>
        </div>
        <!-- 赎回份额输入框 -->
        <div class="redeem_t_b">
          <div class="title_redeem"><span></span>赎回份额</div>
          <div class="input_redeem">
            <input type="text" placeholder="请输入赎回份额" v-model="fund_vol" />
            <i class="iconfont icon-qingkong cancel" v-show="fund_vol != ''" @click.stop.prevent="fund_vol = '';"></i>
          </div>
          <div class="mark_redeem">
            <p>可赎回份额<span> {{redemptionFund.enable_vol}} </span></p>
          </div>
        </div>
      </div>

      <!-- 标注提示和确认赎回按钮 -->
      <div class="redeem_c">
        <p class="mark_redeem">注：模拟基金交易的费率统一为0.4%，在真实操作中费率会根据不同的基金品种、操作有所不同</p>
        <div class="btn_redeem" :class="{active:isActive}" @click.stop.prevent="redeemFund">确认赎回</div>
      </div>

      <!-- 我的持仓列表 -->
      <div class="redeem_b">
        <my-position @chooseFund="clickFund1"></my-position>
      </div>

    </div>

    <!-- 弹出层 -->
    <search-list v-show="isSearch" :searchList="searchList" @chooseFund="clickFund2" @closeLayer="clickShadow"></search-list>

    <fund-commit-modal></fund-commit-modal>
  </div>
</template>

<script>
  import CommonUtil from 'common/common.util'
  import Constant from 'common/constant'
  import LocalDAO from 'common/localDAO'
  import RemoteDAO from 'common/remoteDAO'

  import HeaderTop from 'components/HeaderTop'
  import MyPosition from 'components/fund/MyPosition'
  import SearchList from 'components/fund/SearchList'
  import FundCommitModal from 'components/modal/fund/FundCommitModal'

  export default {
    data () {
      return {
        headerOption: {
          title: '基金赎回',
          leftBtn: Constant.leftBtn.BACK,
          operations: []
        },
        redemptionFund: {
          ofcode: this.$route.query.ofcode ? this.$route.query.ofcode : '',                             //基金代码
          ofname: this.$route.query.ofname ? this.$route.query.ofname : '',                             //基金名称
          ofstatue: this.$route.query.ofstatue ? this.$route.query.ofstatue : '',                       //基金状态
          last_price: this.$route.query.last_price ? this.$route.query.last_price : '',                 //基金净值
          enable_vol: this.$route.query.enable_vol ? this.$route.query.enable_vol : ''                  //可赎回份额
        },
        user_code: LocalDAO.getUserCode(),
        isSearch: false,                    //是否显示搜索列表标志位，默认不显示
        searchList: [],                     //通过基金代码模糊搜索到的基金列表
        fund_code: '',                      //基金代码
        fund_vol: '',                       //赎回份额
        lastNum: '',                        //赎回份额输入有效值存档
        redeemEnd: true                     //点击确认赎回调接口是否结束标志位，避免多次点击调多次接口
      }
    },
    components: {
      HeaderTop,
      MyPosition,
      SearchList,
      FundCommitModal
    },
    computed: {
      //计算确认赎回按钮的显示状态
      isActive () {
        if((this.redemptionFund.ofstatue == "0" || this.redemptionFund.ofstatue == "5") && this.fund_vol != '' && this.fund_vol <= this.redemptionFund.enable_vol){
          return true
        }else{
          return false
        }
      }
    },
    watch: {
      //监听赎回份额输入框输入的内容
      fund_vol () {
        var fund_vol = String(this.fund_vol);
        if(isNaN(fund_vol)){
          fund_vol = fund_vol.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
          fund_vol = fund_vol.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); //保留点一个小数点，去点其他的小数点
          fund_vol = fund_vol.replace(/^(\-)?(\d+)\.(\d\d).*$/, "$1$2.$3");  //保留两位小数
          this.fund_vol = fund_vol;
        }
        if(fund_vol.indexOf('.') > -1 && fund_vol.split('.')[1].length > 2){
          fund_vol = fund_vol.replace(/^(\-)?(\d+)\.(\d\d).*$/, "$1$2.$3");  //保留两位小数
          this.fund_vol = fund_vol;
        }
        if (Number(fund_vol) > Number(this.redemptionFund.enable_vol).toFixed(2)) { //大于剩余资金则转成上次缓存的值
          this.fund_vol = this.lastNum;
        }
        this.lastNum = fund_vol;  //缓存这次的值
      }
    },
    created () {
      this.init();
    },
    methods: {
      //初始化,如果从基金持仓页面点击赎回跳转至基金赎回页面,则在基金代码输入框内显示:ofcode+' '+ofname,如果直接点击基金赎回，则在基金代码输入框为空。
      init () {
        if(this.redemptionFund.ofcode != '' && this.redemptionFund.ofname != ''){
          this.fund_code = this.redemptionFund.ofcode + ' ' + this.redemptionFund.ofname;
          this.getNewEnableVol(this.redemptionFund.ofcode);//获取最新的可赎回份额
        }
      },

      //模糊搜索，在基金代码输入框内输入基金代码或基金名称简拼，显示搜索到的基金列表
      search () {
        if(this.fund_code.length > 1){
          this.isSearch = true;
          RemoteDAO.fundSearch(this.fund_code,response => {
            if(response.error == "0"){
              if(response.data.body.length > 0){
                this.searchList = CommonUtil.translateFundsStatus(response.data.body);
              }else{
                this.searchList = [];
              }
            }else{
              this.$store.dispatch('setTip',{text:response.data})
            }
          })
        }else{
          this.isSearch = false;
        }
        this.resetRedemptionFund();
      },

      //点击清空基金代码输入框的内容
      clearInput () {
        this.fund_code = '';
        this.isSearch = false;
        this.resetRedemptionFund();
      },

      //重置要赎回的基金对象
      resetRedemptionFund () {
        this.redemptionFund.ofcode = '';
        this.redemptionFund.ofname = '';
        this.redemptionFund.ofstatue = '';
        this.redemptionFund.last_price = '';
        this.redemptionFund.enable_vol = '';
      },

      //点击确认赎回
      redeemFund () {
        if(this.isActive && this.redeemEnd){
          this.redeemEnd = false;
          let fund_vol = Number(this.fund_vol);
          let params = {
            clientId: this.user_code,
            tradeType: 4,
            marketCd: 1,
            stockCode: this.redemptionFund.ofcode,
            tradePrice: fund_vol,
            tradeCount: 1,
            bfollow: 0,
            followClient: ''
          };
          RemoteDAO.callJCL11116(params,response => {//基金赎回
            if(response.error == "0"){
              this.resetRedemptionFund();
              this.fund_code = '';
              this.fund_vol = '';
              let params= {
                entrust_type: 1,
                entrust_typeid: "",
                start: 0,
                limit: 20,
                client_id: this.user_code
              };
              RemoteDAO.callJCL11163(params,res => {//委托查询
                if(res.error == "0"){
                  if(res.data.body.records.length > 0){
                    let record = res.data.body.records[0];
                    let ofname = record.ofname;
                    let entrustVol = CommonUtil.toFixed(record.entrust_vol,2);
                    this.$store.dispatch('setModal',{visible:true,entrustBs:4,ofname:ofname,entrustAmt:entrustVol,modalId:Constant.modal.FUND_COMMIT_MODAL});
                  }else{
                    this.$store.dispatch('setTip',{text: '未查询到当日委托'});
                  }
                }else{
                  this.$store.dispatch("setTip",{text:'委托查询：'+res.data})
                }
                this.redeemEnd = true;
              })
            }else{
              this.$store.dispatch('setTip',{text:'基金赎回：'+response.data});
              this.redeemEnd = true;
            }
          })
        }
      },

      //点击我的持仓列表中的基金
      clickFund1 (item) {
        Object.assign(this.redemptionFund,{
          ofcode: item.ofcode,
          ofname: item.ofname,
          ofstatue: item.ofstatue,
          last_price: item.last_price,
          enable_vol: item.enable_vol
        });
        this.getNewEnableVol(item.ofcode);//获取最新的可赎回份额
        this.fund_code = this.redemptionFund.ofcode + ' ' + this.redemptionFund.ofname;
        this.fund_vol = '';
      },

      //击模糊搜索列表中的基金
      clickFund2 (item) {
        this.isSearch = false;
        let params = {
          client_id: this.user_code,
          ofcode: item.ofcode,
          start: 0,
          limit: 20
        };
        RemoteDAO.callJCL11165(params,response => {
          if(response.error == "0"){
            if(response.data.body.records.length > 0){
              var fund = response.data.body.records[0];
              Object.assign(this.redemptionFund,{
                ofcode: fund.ofcode,
                ofname: fund.ofname,
                ofstatue: fund.ofstatue,
                last_price: CommonUtil.toFixed(fund.nav,2),
                enable_vol: "0.00"
              });
              this.getNewEnableVol(fund.ofcode);//获取最新的可赎回份额
            }else{
              this.$store.dispatch('setTip',{text:'未查询到该基金信息'});
              this.resetRedemptionFund();
            }
          }else{
            this.$store.dispatch('setTip',{text:response.data});
            this.resetRedemptionFund();
          }
          this.fund_code = this.redemptionFund.ofcode + ' ' + this.redemptionFund.ofname;
          this.fund_vol = '';
        })
      },

      //获取最新可赎回份额
      getNewEnableVol (ofcode) {
        let params = {
          ofcode: ofcode,
          entrust_bs: 4,
          entrust_type: 1,
          entrust_typeid: '',
          client_id: this.user_code
        };
        RemoteDAO.callJCL11169(params,response => {
          if(response.error == '0'){
            if(response.data.body.enable_vol != undefined && response.data.body.enable_vol != ''){
              Object.assign(this.redemptionFund,{
                enable_vol: CommonUtil.toFixed(response.data.body.enable_vol,2)
              });
            }
          }else{
            this.$store.dispatch('setTip',{text:response.data})
          }
        })
      },

      //点击模糊搜索列表蒙层隐藏搜索弹框
      clickShadow (flag) {
        this.isSearch = flag
      }
    },
    filters: {
      //获取基金状态（认购、申购、赎回）
      getStatusName (ofstatue) {
        var statusName = "";
        switch(String(ofstatue)){
          case "0" : statusName = "可申购赎回"; break;
          case "1" : statusName = "发行"; break;
          case "4" : statusName = "停止申购赎回"; break;
          case "5" : statusName = "停止申购"; break;
          case "6" : statusName = "停止赎回"; break;
          case "8" : statusName = "基金终止"; break;
          case "9" : statusName = "基金封闭"; break;
          default  : statusName = "其他"; break;
        }
        return statusName;
      }
    }
  }
</script>

<style scoped>
  * {
    margin: 0;
    padding: 0;
  }
  .fixed {
    position: fixed;
    left: 0;
    right: 0;
    top: 44px;
    bottom: 0;
  }
  .title_redeem {
    padding-bottom: 6px;
    font-size: 15px;
    line-height: 0;
    box-sizing: border-box;
  }
  .title_redeem span {
    display: inline-block;
    width: 3px;
    height: 12px;
    border-radius: 2px;
    margin-right: 4px;
    background: #33a7f1;
    position: relative;
  }
  .mark_redeem {
    font-size: 12px;
    line-height: 14px;
    color: #999;
    padding-left: 9px;
  }

  /****** 顶部 ******/
  .redeem_t {
    height: 237px;
    padding: 22px 10% 0;
    box-sizing: border-box;
    background: #fff;
  }
  .redeem_t_t {
    height: 116px;
  }
  .redeem_t_b {
    height: auto;
  }
  .input_redeem {
    width: 100%;
    height: 45px;
    line-height: 45px;
    margin-bottom: 5px;
    border: 1px solid #999;
    border-radius: 5px;
    background: #fff;
    position: relative;
    overflow: hidden;
  }
  .redeem_t .fund_code {
    z-index: 1031;
  }
  .redeem_t .input_redeem input {
    display: block;
    width: 90%;
    height: 100%;
    border: none;
    outline: none;
    text-indent: 8px;
    font-size: 14px;
    color: #565656;
    overflow: hidden;
  }
  .redeem_t .input_redeem i {
    display: block;
    width: 10%;
    height: 100%;
    position: absolute;
    left: 90%;
    top: 0;
    text-align: center;
    line-height: 45px;
    font-size: 24px;
    color: #999;
  }

  /****** 中部 ******/
  .redeem_c {
    height: 151px;
    padding: 26px 10% 0;
    border-top: 1px solid #E6E8E7;
    box-sizing: border-box;
    background: #F2F2F2
  }
  .redeem_c .btn_redeem {
    height: 36px;
    margin-top: 18px;
    background-color: #999;
    border-radius: 5px;
    font-size: 16px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .redeem_c .btn_redeem.active {
    background-color: #3e7be6;
  }

  /****** 底部 ******/
  .redeem_b {
    position: absolute;
    left: 0;
    right: 0;
    top: 432px;
    bottom: 0;
    background: #fff;
  }
  @media screen and (max-height: 666px){
    .redeem_b {
      position: static;
      height: 230px;
    }
  }

</style>
